import {Component, OnInit, Input} from '@angular/core';
// import * as Highcharts from 'highcharts';

import {NavController, ActionSheetController, AlertController} from 'ionic-angular';
import {DomSanitizer} from '@angular/platform-browser';
import _ from "lodash";
import {IrpHotStockHomeService} from "./home.service";
import {Common} from "../../../../providers/common";
import {IrpHotStockHMorePage} from "../more/more.component";

@Component({
  selector: "page-irp-panoramagram-home",
  templateUrl: 'home.html',
  providers: [IrpHotStockHomeService]
})
export class IrpHotStockHomePage {
  Title_CompanyScaleTrend = {
    all_capitalColor: "",
    gm_capitalColor: "",
    sb_capitalColor: "",
    zh_capitalColor: "",
    all_capital: null,
    all_capitalDiff: null,
    gm_capital: null,
    gm_capitalDiff: null,
    sb_capital: null,
    sb_capitalDiff: null,
    zh_capital: null,
    zh_capitalDiff: null
  };
  Title_GMGoin = {
    allcapitalColor: "",
    huobcapitalColor: "",
    nhuobcapitalColor: "",
    allcapital: null,
    huobcapital: null,
    nhuobcapital: null,
    allcapitalDiff: null,
    huobcapitalDiff: null,
    nhuobcapitalDiff: null
  };
  Title_ImportantChancel = {
    up: [],
    down: []
  };
  Title_ImportantOrganization = {
    up: [],
    down: []
  };
  Title_GMProductInvest = {
    up: [],
    down: []
  };
  Title_ZHProductInvest = {
    up: [],
    down: []
  };

  isAdmin = false;

  currentDate = "";
  ResearchReportdatasList=[];

  constructor(public navCtrl: NavController,
              public alertCtrl: AlertController,
              public homeService: IrpHotStockHomeService,
              private sanitizer: DomSanitizer,
              private actionSheetCtrl: ActionSheetController,
              public common: Common) {
  }

  ngAfterViewInit() {
    // setTimeout(() => {
    //   this.homeService.getDataGridFromRedis().subscribe(result => {
    //     this.isAdmin = result.isAdmin;
    //     this.initDataGrid(result);
    //   });
    // }, 1000);
    this.initDataGrid("");

  }

  initDataGrid(result) {
    this.ResearchReportdatasList = [{changecapital: '35',growthRate:"8", managername: "万科A（000002）"}, {
      changecapital: '39',growthRate:"9",
      managername: "世纪星源（000005）"
    }, {changecapital: '38', growthRate:"15",managername: "东风汽车（600006）"}, {changecapital: '37',growthRate:"20", managername: "南京高科（600064）"}, {
      changecapital: '35',growthRate:"18",
      managername: "中国国贸（600007）"
    }];


    this.ImportantOrganization(this.ResearchReportdatasList, "ResearchReport", 10);

  }


  goMore() {
    this.navCtrl.push(IrpHotStockHMorePage);
  }

  ImportantOrganization(datas, dom, count) {

    let series = [];
    let dw="次";
    let title="热点研究股票";
    console.log(datas);
    // let titleDatas = [];
    // _.forEach(datas, (data, i) => {

      // temp_series.data[parseInt(i)] = parseFloat(data["changecapital"]);
      // console.log(temp_series)
      // changecapital.push(parseFloat(data.changecapital));
      // growthRate.push(parseFloat(data.growthRate));
      //data["changecapital"] = parseFloat(parseFloat(data["changecapital"]).toFixed(2));
      // data["changecapital"] = parseFloat(data["changecapital"]);
      // let temp = "";
      // if (parseFloat(data["changecapital"]) > count) {

        // temp = "<span style='color: red;'>" + data["changecapital"] + dw + "</span>";
      // } else {
      //   temp_series["name"] = data["managername"];
      //   temp_series["color"] = "#7CB5EC";
      //   temp = "<span style='color: green;'>" + _.replace(data["changecapital"], "-", "") + dw + "</span>";
      // }
      // series.push(temp_series);
      // titleDatas.push(temp);
    // });
    let changecapital =_.map(datas, "changecapital");
    let growthRate=_.map(datas, "growthRate");
    _.forEach(changecapital,(d:any,i)=>{
      changecapital[i]=parseFloat(d);
    })
    _.forEach(growthRate,(d:any,i)=>{
      growthRate[i]=parseFloat(d);
    })
    let temp_series = {
      name: "研究次数",
      color:"#FFB03B",
      data: changecapital
    };
    let temp_growthRate = {
      name: "增长率",
      color:"red",
      data: growthRate
    };
    series.push(temp_series);
    series.push(temp_growthRate);
    console.log(_.map(datas, "managername"))
    console.log(series);
    this.Title_ImportantOrganization.up = [];
    this.Title_ImportantOrganization.down = [];
    _.forEach(datas, (td, i: number) => {
      let temp = {
        color: "",
        name: "",
        data: null
      };
      temp.name = td["managername"];
      temp.data = td["changecapital"];
      temp.color = +temp.data > count ? "redColor" : "greenColor";
      temp.data = _.replace(temp.data, "-", "");
      if (i < 5) {
        this.Title_ImportantOrganization.up.push(temp);
      } else {
        this.Title_ImportantOrganization.down.push(temp);
      }
    });

    /*this.Title_ImportantOrganization = "截至" + this.currentDate + "，近一个月重点机构规模变动中，" +
     up + "处于上涨区间，" + down + "处于下行区间。";

     this.Title_ImportantOrganization = this.sanitizer.bypassSecurityTrustHtml(this.Title_ImportantOrganization);*/

    let elements = document.getElementsByClassName(dom);
    _.forEach(elements, el => {
      window["Highcharts"].chart({
        chart: {
          renderTo: el,
          type: 'bar'
        },
        title: {
          text:''
        },
        subtitle: {
          text: title,
          style:'font-weight:bold'
        },
        xAxis: {
          categories: _.map(datas, "managername"),
          labels: {
            // align:'center',
            // rotation: -45
            style:"text-align:center",
            formatter: function() {
              var labelVal = this.value;
              var reallyVal = labelVal;
              var lvl = labelVal.length;
              var i=labelVal.indexOf('（');
              console.log(i);
              reallyVal = labelVal.substr(0,i)+"<br/>"+labelVal.substring(i,lvl);
              // if(lvl > 8 && lvl <=16){
              //   reallyVal = labelVal.substr(0,8)+"<br/>"+labelVal.substring(8,lvl);
              // }else if(lvl > 16 && lvl <=24){
              //   reallyVal = labelVal.substr(0,8)+"<br/>"+labelVal.substr(8,8)+"<br/>"+labelVal.substring(16,lvl);
              // }else if(lvl > 24){
              //   reallyVal = labelVal.substr(0,8)+"<br/>"+labelVal.substr(8,8)+"<br/>"+labelVal.substr(16,8)+"<br/>"+labelVal.substring(24,lvl);
              // }
              return reallyVal;
            }
          }
        },
        plotOptions: {
          column: {
            stacking: 'normal'
          }
        },
        yAxis: {
          title: {
            align: "high",
            // rotation: 0,
            // offset: 0,
            // y: 10,
            margin:10,
            // x: 50,
            text: '研究数/增长率（次/%）',
          }
          // labels: {
          //   overflow: 'justify'
          // }
        },
        navigation: {
          buttonOptions: {
            enabled: false
          }
        },
        legend: {
          verticalAlign: 'bottom',
          // layout: 'vertical',
          align: 'center',
          // x: 0,
          // y: 15,
          // floating: true,
          // borderWidth: 1,
          // backgroundColor: ( '#FFFFFF'),
          // shadow: true
          // margin: 35,
          // enabled: false
        },
        tooltip: {
          pointFormatter: function () {
            this.n="次";
            if(this.series.name=="增长率"){
              this.n="%"
            }
            return '<span style="color:{' + this.series.color + '}>'+this.series.name+'</span> : <b>'+this.y+'</b>'+this.n+'<br/>.'
          }
        },
        series: series

      });
    });
  }


}

